<template>
  <div class="purchase-return-order">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="退货单号">
            <el-input v-model="searchForm.returnNo" placeholder="请输入退货单号" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="草稿" :value="0" />
              <el-option label="已提交" :value="1" />
              <el-option label="审核通过" :value="2" />
              <el-option label="审核驳回" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="operation-area">
        <el-button type="primary" @click="handleAdd">新增退货单</el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
          批量删除
        </el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="returnNo" label="退货单号" width="180" />
        <el-table-column prop="orderNo" label="采购订单号" width="180" />
        <el-table-column prop="creatorName" label="创建人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="statusDesc" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.statusDesc }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalReturnAmount" label="退货总金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalReturnAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <!-- 将 查看 改为 删除 -->
            <el-button type="text" @click="handleDelete(row)">删除</el-button>
            <el-button 
              v-if="row.status === 0" 
              type="text" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            
            <!-- 移除 提交审核 按钮 -->
            
            <el-button 
              v-if="row.status === 0" 
              type="text" 
              type="danger" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="采购订单" prop="orderId">
          <el-select v-model="form.orderId" placeholder="请选择采购订单" filterable>
            <el-option
              v-for="order in orderOptions"
              :key="order.id"
              :label="order.orderNo"
              :value="order.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="退货总金额" prop="totalReturnAmount">
          <el-input-number
            v-model="form.totalReturnAmount"
            :precision="2"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
        
        <!-- 退货商品列表 -->
        <el-form-item label="退货商品">
          <div class="items-table">
            <el-button type="primary" @click="handleAddItem">添加商品</el-button>
            <el-table :data="form.items" border style="margin-top: 10px">
              <el-table-column prop="productName" label="商品名称" />
              <el-table-column prop="returnQuantity" label="退货数量" width="120">
                <template #default="{ row, $index }">
                  <el-input-number
                    v-model="row.returnQuantity"
                    :min="1"
                    @change="calculateItemAmount(row, $index)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="returnPrice" label="退货单价" width="120">
                <template #default="{ row, $index }">
                  <el-input-number
                    v-model="row.returnPrice"
                    :precision="2"
                    :min="0"
                    @change="calculateItemAmount(row, $index)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="returnAmount" label="退货金额" width="120">
                <template #default="{ row }">
                  ¥{{ row.returnAmount }}
                </template>
              </el-table-column>
              <el-table-column prop="reason" label="退货原因" width="200">
                <template #default="{ row }">
                  <el-input v-model="row.reason" placeholder="请输入退货原因" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button type="text" @click="handleRemoveItem($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="退货单详情"
      width="800px"
    >
      <div v-if="detailData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="退货单号">{{ detailData.returnNo }}</el-descriptions-item>
          <el-descriptions-item label="采购订单号">{{ detailData.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ detailData.creatorName }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(detailData.status)">{{ detailData.statusDesc }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="退货总金额">¥{{ detailData.totalReturnAmount }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '-' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 退货商品列表 -->
        <div style="margin-top: 20px;">
          <h4>退货商品</h4>
          <el-table :data="detailData.items" border>
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="returnQuantity" label="退货数量" width="100" />
            <el-table-column prop="returnPrice" label="退货单价" width="120" />
            <el-table-column prop="returnAmount" label="退货金额" width="120" />
            <el-table-column prop="reason" label="退货原因" />
          </el-table>
        </div>

        <!-- 审核信息 -->
        <div v-if="detailData.auditInfo" style="margin-top: 20px;">
          <h4>审核信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="审核人">{{ detailData.auditInfo.auditorName }}</el-descriptions-item>
            <el-descriptions-item label="审核时间">{{ detailData.auditInfo.auditTime }}</el-descriptions-item>
            <el-descriptions-item label="审核结果">
              <el-tag :type="detailData.auditInfo.auditResult === 1 ? 'success' : 'danger'">
                {{ detailData.auditInfo.auditResultDesc }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="审核意见">{{ detailData.auditInfo.auditOpinion || '-' }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const detailData = ref(null)

// 搜索表单
const searchForm = reactive({
  returnNo: '',
  status: null
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const form = reactive({
  id: null,
  orderId: null,
  totalReturnAmount: 0,
  remark: '',
  items: []
})

// 表单验证规则
const rules = {
  orderId: [{ required: true, message: '请选择采购订单', trigger: 'change' }],
  totalReturnAmount: [{ required: true, message: '请输入退货总金额', trigger: 'blur' }]
}

// 采购订单选项
const orderOptions = ref([])

// 表单引用
const formRef = ref()

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const response = await axios.get('/purchase-return-order/page', {
      params: {
        current: pagination.current,
        size: pagination.size,
        status: searchForm.status,
        returnNo: searchForm.returnNo
      }
    })
    
    if (response.data.success) {
      tableData.value = response.data.data.records
      pagination.total = response.data.data.total
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 获取采购订单选项
const fetchOrderOptions = async () => {
  try {
    const response = await axios.get('/purchase-order/page', {
      params: { current: 1, size: 1000 }
    })
    if (response.data.success) {
      orderOptions.value = response.data.data.records
    }
  } catch (error) {
    console.error('获取采购订单失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    returnNo: '',
    status: null
  })
  pagination.current = 1
  fetchData()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增退货单'
  Object.assign(form, {
    id: null,
    orderId: null,
    totalReturnAmount: 0,
    remark: '',
    items: []
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑退货单'
  Object.assign(form, {
    id: row.id,
    orderId: row.orderId,
    totalReturnAmount: row.totalReturnAmount,
    remark: row.remark,
    items: []
  })
  // TODO: 获取退货商品列表
  dialogVisible.value = true
}

// 查看
const handleView = async (row) => {
  try {
    const response = await axios.get(`/purchase-return-order/${row.id}`)
    if (response.data.success) {
      detailData.value = response.data.data
      detailDialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

// 提交审核
const handleSubmit = async (row) => {
  try {
    await ElMessageBox.confirm('确定要提交审核吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.post(`/purchase-return-order/submit/${row.id}`)
    if (response.data.success) {
      ElMessage.success('提交成功')
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('提交失败')
    }
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个退货单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete(`/purchase-return-order/${row.id}`)
    if (response.data.success) {
      ElMessage.success('删除成功')
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的退货单')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个退货单吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(row => row.id)
    const response = await axios.delete('/purchase-return-order/batch', { data: ids })
    if (response.data.success) {
      ElMessage.success('删除成功')
      selectedRows.value = []
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  fetchData()
}

// 当前页变化
const handleCurrentChange = (current) => {
  pagination.current = current
  fetchData()
}

// 添加商品
const handleAddItem = () => {
  form.items.push({
    orderItemId: null,
    returnQuantity: 1,
    returnPrice: 0,
    returnAmount: 0,
    reason: ''
  })
}

// 删除商品
const handleRemoveItem = (index) => {
  form.items.splice(index, 1)
}

// 计算商品金额
const calculateItemAmount = (row, index) => {
  row.returnAmount = row.returnQuantity * row.returnPrice
  // 重新计算总金额
  form.totalReturnAmount = form.items.reduce((sum, item) => sum + item.returnAmount, 0)
}

// 保存
const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    if (form.items.length === 0) {
      ElMessage.warning('请添加退货商品')
      return
    }
    
    const response = await axios.post('/purchase-return-order/create', form)
    if (response.data.success) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      fetchData()
    }
  } catch (error) {
    console.error('保存失败:', error)
  }
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'info',    // 草稿
    1: 'warning', // 已提交
    2: 'success', // 审核通过
    3: 'danger'   // 审核驳回
  }
  return types[status] || 'info'
}

// 初始化
onMounted(() => {
  fetchData()
  fetchOrderOptions()
})
</script>

<style scoped>
.purchase-return-order {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.items-table {
  width: 100%;
}

.el-table {
  margin-top: 10px;
}
</style> 